#Qt相关模块
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtCore import QPoint, Qt
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsDropShadowEffect
from PyQt5.QtCore import QPropertyAnimation,QRect,Qt,QThread, QParallelAnimationGroup
from PyQt5.QtWidgets import QLabel
from PyQt5.QtCore import pyqtSignal

#Qt以外模块
import sys, os, time, threading
import global_var
from threading import Thread
from openpyxl import Workbook
import numpy
from yaml import DirectiveToken

#和其他文件链接
from PDS_Window_ui import Ui_PDS_Window
from test2 import all


class Connect_PDS_Window(Ui_PDS_Window, QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        
        self.setFixedSize(self.width(), self.height())#固定窗口大小，使窗口大小无法改变
        self.setWindowOpacity(1) # 设置窗口透明度
        self.setWindowFlags(Qt.FramelessWindowHint)  # 去边框
        self.setAttribute(Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        
        self.pushButton.clicked.connect(self.mini)#最小化按钮
        self.pushButton_14.clicked.connect(self.exit)#关闭窗口按钮
        
        self.pushButton_2.clicked.connect(self.result)#页面1
        self.pushButton_3.clicked.connect(self.analysis)#页面2
        self.pushButton_4.clicked.connect(self.out)#页面3
        self.pushButton_7.clicked.connect(self.result)
        self.pushButton_8.clicked.connect(self.analysis)
        self.pushButton_9.clicked.connect(self.out)
        self.pushButton_17.clicked.connect(self.exportToExcel) #导出表单按钮
        

        self.pushButton_12.clicked.connect(self.HiddenSignal)    #利用Qthread
        self.widget_16.hide()
        self.hidden_init()   #初始化导航栏抽屉动画
        self.m_flag=False
        
        self.add_shadow()
        
#实现窗口移动
    def mousePressEvent(self, event):
        if event.button()==Qt.LeftButton:
            self.m_flag=True
            self.m_Position=event.globalPos()-self.pos() #获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(Qt.OpenHandCursor)  #更改鼠标图标
        
    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:  
            self.move(QMouseEvent.globalPos()-self.m_Position)#更改窗口位置
            QMouseEvent.accept()
            
    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag=False
        self.setCursor(Qt.ArrowCursor)

    
#实现导航栏缩放
    def HiddenSignal(self):#缩放按钮信号连接槽函数
        # Thread = threading.Thread(target=self.hidden,args=(1,))
        self.hidden_Thread.start()

    def hidden_init(self):#设置导航栏缩放动画
        self.hidden_state=0
        self.hidden_Thread=hiddenThread(self)
        
        self.anim = QPropertyAnimation(self.label_4, b"geometry")
        self.anim.setDuration(50)
        self.anim.setStartValue(QRect(0, 15, 60, 60))
        self.anim.setEndValue(QRect(0, 15, 42, 42))
        self.anim2 = QPropertyAnimation(self.navigation, b"geometry")
        self.anim2.setDuration(50)
        self.anim2.setStartValue(QRect(0, 90, 171, 552))
        self.anim2.setEndValue(QRect(0, 90, 41, 552))
        self.anim3 = QPropertyAnimation(self.pushButton_12, b"geometry")
        self.anim3.setDuration(50)
        self.anim3.setStartValue(QRect(120, 10, 40, 40))
        self.anim3.setEndValue(QRect(0, 10, 40, 40))       
        self.anim4 = QPropertyAnimation(self.widget_2, b"geometry")
        self.anim4.setDuration(50)
        self.anim4.setStartValue(QRect(0, 0, 171, 91))
        self.anim4.setEndValue(QRect(0, 0, 41, 91))
        self.anim5 = QPropertyAnimation(self.stackedWidget, b"geometry")
        self.anim5.setDuration(50)
        self.anim5.setStartValue(QRect(171, 44, 801, 595))
        self.anim5.setEndValue(QRect(41, 44, 931, 595))
        self.anim6 = QPropertyAnimation(self.widget_15, b"geometry")    #最小化，退出按钮栏
        self.anim6.setDuration(50)
        self.anim6.setStartValue(QRect(172,0,721,40))
        self.anim6.setEndValue(QRect(41, 0, 850, 40))

        self.anim7 = QPropertyAnimation(self.label_4, b"geometry")
        self.anim7.setDuration(50)
        self.anim7.setStartValue(QRect(0, 15, 42, 42))
        self.anim7.setEndValue(QRect(0, 15, 60, 60))
        self.anim8 = QPropertyAnimation(self.navigation, b"geometry")
        self.anim8.setDuration(50)
        self.anim8.setStartValue(QRect(0, 90, 41, 552))
        self.anim8.setEndValue(QRect(0, 90, 171, 552))
        self.anim9 = QPropertyAnimation(self.pushButton_12, b"geometry")
        self.anim9.setDuration(50)
        self.anim9.setStartValue(QRect(0, 10, 40, 40))
        self.anim9.setEndValue(QRect(120, 10, 40, 40))       
        self.anim10 = QPropertyAnimation(self.widget_2, b"geometry")
        self.anim10.setDuration(50)
        self.anim10.setStartValue(QRect(0, 0, 41, 91))
        self.anim10.setEndValue(QRect(0, 0, 171, 91))
        self.anim11 = QPropertyAnimation(self.stackedWidget, b"geometry")
        self.anim11.setDuration(50)
        self.anim11.setStartValue(QRect(41, 44, 931, 595))
        self.anim11.setEndValue(QRect(171, 44, 801, 595))
        self.anim12 = QPropertyAnimation(self.widget_15, b"geometry") #最小化，关闭按钮栏
        self.anim12.setDuration(50)
        self.anim12.setStartValue(QRect(41, 0, 850, 40))
        self.anim12.setEndValue(QRect(172,0,721,40))

        self.animGroup1=QParallelAnimationGroup(self)
        self.animGroup2=QParallelAnimationGroup(self)
        self.animGroup1.addAnimation(self.anim)
        self.animGroup1.addAnimation(self.anim2)
        self.animGroup1.addAnimation(self.anim3)
        self.animGroup1.addAnimation(self.anim4)
        self.animGroup1.addAnimation(self.anim5)
        self.animGroup1.addAnimation(self.anim6)
        self.animGroup2.addAnimation(self.anim7)
        self.animGroup2.addAnimation(self.anim8)
        self.animGroup2.addAnimation(self.anim9)
        self.animGroup2.addAnimation(self.anim10)
        self.animGroup2.addAnimation(self.anim11)
        self.animGroup2.addAnimation(self.anim12)

    def hidden(self):   #实现导航栏缩放

        if self.hidden_state==0:
            self.hidden_state=1
            self.animGroup1.start()     #加了thread下面要反过来，可能是Qthread和animation冲突
            self.widget_16.hide()
            self.widget.show()

        else:
            self.hidden_state=0
            self.animGroup2.start()
            self.widget.hide()
            self.widget_16.show()

#外观函数
    def add_shadow(self):
        self.effect_shadow = QGraphicsDropShadowEffect(self)
        self.effect_shadow.setOffset(4,4) # 偏移
        self.effect_shadow.setBlurRadius(20) # 阴影半径
        self.effect_shadow.setColor(QColor(0,0,0,100)) # 阴影颜色
        self.setGraphicsEffect(self.effect_shadow) # 将设置套用到widget窗口中,导致抽屉栏收放卡顿

#导航栏按钮，最小化，退出按钮连接槽函数       
    def result(self):
        self.pushButton_2.setChecked(True)
        self.pushButton_3.setChecked(False)
        self.pushButton_4.setChecked(False)
        #       小icon
        self.pushButton_7.setChecked(True)
        self.pushButton_8.setChecked(False)
        self.pushButton_9.setChecked(False)
        self.stackedWidget.setCurrentIndex(0)

    def analysis(self):
        self.pushButton_2.setChecked(False)
        self.pushButton_3.setChecked(True)
        self.pushButton_4.setChecked(False)
       #       小icon
        self.pushButton_7.setChecked(False)
        self.pushButton_8.setChecked(True)
        self.pushButton_9.setChecked(False)
        self.stackedWidget.setCurrentIndex(1)

    def out(self):
        self.pushButton_2.setChecked(False)
        self.pushButton_3.setChecked(False)
        self.pushButton_4.setChecked(True)
       #       小icon
        self.pushButton_7.setChecked(False)
        self.pushButton_8.setChecked(False)
        self.pushButton_9.setChecked(True)
        self.stackedWidget.setCurrentIndex(2)
    
    def exit(self):         #退出
        self.close()
        # def Thread():
        #     for i in reversed(range(0, 11)):
        #         self.setWindowOpacity(i / 10)
        #         time.sleep(0.03)                    #渐渐隐去效果
        #     os._exit(-1)
        # Thread = threading.Thread(target=Thread)
        # Thread.start()
        

    def mini(self):
        self.showMinimized()
        #上面mac风格,下面window风格
        # def Thread():
        #     for i in reversed(range(0, 11)):
        #         self.setWindowOpacity(i / 10)
        #         time.sleep(0.03)                    #渐渐隐去效果
        #     self.showMinimized()
        #     self.setWindowOpacity(1)
        # Thread = threading.Thread(target=Thread)
        # Thread.start()
   
#1、2页所有节点按钮
    def Grid_Button(self,dict_in,rootnode):
        self.data = global_var.get_value('data') 
        
        for key in dict_in.keys():
            dict_in[key][-1] = 0
            dict_in[key].append(0)
        #print(len(dict_in['5']))

        list=[]  #上级节点的记录
        dict_internal = {}

        def Tree(self,node):
            # print(node)
            # print(list)
            a = dict_in[node][-2] #记录该节点执行次数
            #print(a)
            if len(dict_in[node]) == 2: 
                list.append(node)
                for i in range(len(list)):
                    if dict_in[list[i]][-1] == 0:
                        dict_in[list[i]][-1] = 1
                        if i == 0:
                            dict_internal["item_0"] = globals()["item_0"] = QtWidgets.QTreeWidgetItem(self.treeWidget)
                            b = "item_0"
                            #print(b)
                        else:
                            c = "item_" + str(i) + "_" + str(dict_in[list[i-1]][-2])
                            #print(c)
                            dict_internal[c] = globals()[c] = QtWidgets.QTreeWidgetItem(dict_internal[b])
                            b = c
                            #print(b)
                    else:
                        if i == 0:
                            b = "item_0"
                            #print(b)
                        else:
                            b = "item_" + str(i) + "_" + str(dict_in[list[i-1]][-2])  
                            #print(b) 
                del list[-1]
                dict_in[node][-2] += 1
                dict_in[list[-1]][-2] += 1
                #print(list)
                return Tree(self,list[-1])

            elif a < len(dict_in[node]) - 2:
                if list == []:
                    list.append(node)
                elif list[-1] != node:
                    list.append(node)
                return Tree(self,dict_in[node][a])

            elif a == len(dict_in[node]) - 2:
                del list[-1]
                if node == rootnode:
                    return 0
                else:
                    dict_in[list[-1]][-2] += 1
                    return Tree(self,list[-1])

        Tree(self,rootnode)
        self.retranslateUi_1(dict_in,rootnode)
        self.treeWidget.itemClicked['QTreeWidgetItem*','int'].connect(self.Page4_Select)


        for key in dict_in.keys():
            dict_in[key][-1] = 0
            dict_in[key][-2] = 0

        list=[]  #上级节点的记录
        dict_internal = {}

        def Tree_2(self,node):
            #print(node)
            #print(list)
            a = dict_in[node][-2] #记录该节点执行次数
            if len(dict_in[node]) == 2: 
                list.append(node)
                for i in range(len(list)):
                    if dict_in[list[i]][-1] == 0:
                        dict_in[list[i]][-1] = 1
                        if i == 0:
                            dict_internal["Item_0"] = globals()["Item_0"] = QtWidgets.QTreeWidgetItem(self.treeWidget_2)
                            b = "Item_0"
                            #print(b)
                        else:
                            c = "Item_" + str(i) + "_" + str(dict_in[list[i-1]][-2])
                            #print(c)
                            dict_internal[c] = globals()[c] = QtWidgets.QTreeWidgetItem(dict_internal[b])
                            b = c
                            #print(b)
                    else:
                        if i == 0:
                            b = "Item_0"
                            #print(b)
                        else:
                            b = "Item_" + str(i) + "_" + str(dict_in[list[i-1]][-2])  
                            #print(b) 
                del list[-1]
                dict_in[node][-2] += 1
                dict_in[list[-1]][-2] += 1
                #print(list)
                return Tree_2(self,list[-1])

            elif a < len(dict_in[node]) - 2:
                if list == []:
                    list.append(node)
                elif list[-1] != node:
                    list.append(node)
                return Tree_2(self,dict_in[node][a])

            elif a == len(dict_in[node]) - 2:
                del list[-1]
                if node == rootnode:
                    return 0
                else:
                    dict_in[list[-1]][-2] += 1
                    return Tree_2(self,list[-1])

        Tree_2(self,rootnode)
        self.retranslateUi_2(dict_in,rootnode)
        self.treeWidget_2.itemClicked['QTreeWidgetItem*','int'].connect(self.Page2_Select)
        

    def retranslateUi_1(self,dict_in,rootnode):
        _translate = QtCore.QCoreApplication.translate
        self.treeWidget.headerItem().setText(0, _translate("MainWindow", "节点"))

        for key in dict_in.keys():
            dict_in[key][-1] = 0
            dict_in[key][-2] = 0

        list=[]  #上级节点的记录

        def TreeLabel(self,node):
            #print(node)
            #print(list)
            a = dict_in[node][-2] #记录该节点执行次数
            if len(dict_in[node]) == 2: 
                list.append(node)
                for i in range(len(list)):
                    if dict_in[list[i]][-1] == 0:
                        dict_in[list[i]][-1] = 1
                        if i == 0:
                            self.treeWidget.topLevelItem(0).setText(0, _translate("MainWindow", list[i]))
                            b = self.treeWidget.topLevelItem(0)
                            c = dict_in[list[i]][-2]
                        else:
                            b.child(c).setText(0, _translate("MainWindow", list[i]))
                            b = b.child(c)
                            c = dict_in[list[i]][-2]
                    else:
                        if i == 0:
                            b = self.treeWidget.topLevelItem(0)
                            c = dict_in[list[i]][-2]
                        else:
                            b = b.child(c)
                            c = dict_in[list[i]][-2]
                del list[-1]
                dict_in[node][-2] += 1
                dict_in[list[-1]][-2] += 1
                #print(list)
                return TreeLabel(self,list[-1])

            elif a < len(dict_in[node]) - 2:
                if list == []:
                    list.append(node)
                elif list[-1] != node:
                    list.append(node)
                return TreeLabel(self,dict_in[node][a])

            elif a == len(dict_in[node]) - 2:
                del list[-1]
                if node == rootnode:
                    return 0
                else:
                    dict_in[list[-1]][-2] += 1
                    return TreeLabel(self,list[-1])

        TreeLabel(self,rootnode)

        __sortingEnabled = self.treeWidget.isSortingEnabled()
        self.treeWidget.setSortingEnabled(False)

        self.treeWidget.setSortingEnabled(__sortingEnabled)


    def retranslateUi_2(self,dict_in,rootnode):
        _translate = QtCore.QCoreApplication.translate
        self.treeWidget_2.headerItem().setText(0, _translate("MainWindow", "节点"))

        for key in dict_in.keys():
            dict_in[key][-1] = 0
            dict_in[key][-2] = 0

        list=[]  #上级节点的记录

        def TreeLabel(self,node):
            #print(node)
            #print(list)
            a = dict_in[node][-2] #记录该节点执行次数
            if len(dict_in[node]) == 2: 
                list.append(node)
                for i in range(len(list)):
                    if dict_in[list[i]][-1] == 0:
                        dict_in[list[i]][-1] = 1
                        if i == 0:
                            self.treeWidget_2.topLevelItem(0).setText(0, _translate("MainWindow", list[i]))
                            b = self.treeWidget_2.topLevelItem(0)
                            c = dict_in[list[i]][-2]
                        else:
                            b.child(c).setText(0, _translate("MainWindow", list[i]))
                            b = b.child(c)
                            c = dict_in[list[i]][-2]
                    else:
                        if i == 0:
                            b = self.treeWidget_2.topLevelItem(0)
                            c = dict_in[list[i]][-2]
                        else:
                            b = b.child(c)
                            c = dict_in[list[i]][-2]
                del list[-1]
                dict_in[node][-2] += 1
                dict_in[list[-1]][-2] += 1
                #print(list)
                return TreeLabel(self,list[-1])

            elif a < len(dict_in[node]) - 2:
                if list == []:
                    list.append(node)
                elif list[-1] != node:
                    list.append(node)
                return TreeLabel(self,dict_in[node][a])

            elif a == len(dict_in[node]) - 2:
                del list[-1]
                if node == rootnode:
                    return 0
                else:
                    dict_in[list[-1]][-2] += 1
                    return TreeLabel(self,list[-1])

        TreeLabel(self,rootnode)

        __sortingEnabled = self.treeWidget.isSortingEnabled()
        self.treeWidget.setSortingEnabled(False)

        self.treeWidget.setSortingEnabled(__sortingEnabled)


#第2页所有节点按钮连接槽函数及判断逻辑    
    def Page2_Select(self,item,column):
        _translate = QtCore.QCoreApplication.translate
        self.data = global_var.get_value('data')
        #button = self.widget_4.sender()
        #self.nowp = button.text()
        self.nowp = item.text(0)
        self.widget_3.setStyleSheet("QWidget{background-color:white;}")
        self.widget_6.setStyleSheet("QWidget{background-color:white;}")
        self.widget_18.setStyleSheet("QWidget{background-color:white;}")
        self.label_23.setText(_translate("Connect_PDS_Window",''))
        self.label_24.setText(_translate("Connect_PDS_Window",''))
        self.label_25.setText(_translate("Connect_PDS_Window",''))
        self.label_26.setText(_translate("Connect_PDS_Window",' ')) 
        self.label_37.setText(_translate("Connect_PDS_Window",' '))        
        
        self.label_37.setText(_translate("Connect_PDS_Window",'问题所在：' + str(self.data[self.nowp]['问题所在'][0])))
        if self.data[self.nowp]['问题所在'][0] == '上级节点评估等级为红色':
            pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Red' + '.png')
            self.label_21.setPixmap(pixmap)
            if self.data[self.nowp]['上级节点'] == '':
                self.data[self.nowp]['上级节点'] = '无'
            self.label_22.setText(_translate("Connect_PDS_Window",'问题所在：上级节点评估等级为红色\n上级节点:' + self.data[self.nowp]['上级节点']))
            self.widget_3.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}")
            self.widget_6.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}")
            self.widget_18.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}")       
        else:
            pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Green' + '.png')
            self.label_21.setPixmap(pixmap)
            self.label_22.setText(_translate("Connect_PDS_Window",'正常'))
            if self.data[self.nowp]['短路电流校核'] == '通过':
                self.label_23.setText(_translate("Connect_PDS_Window",'通过'))
                if self.data[self.nowp]['电压偏差校核'] == '通过':
                    self.label_24.setText(_translate("Connect_PDS_Window",'通过'))
                    self.label_25.setText(_translate("Connect_PDS_Window",self.data[self.nowp]['反向负载率百分比']))
                    if self.data[self.nowp]['评估等级'] == '绿色':
                        pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Green' + '.png')
                        self.label_26.setPixmap(pixmap)
                    elif self.data[self.nowp]['评估等级'] == '黄色':
                        pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Yellow' + '.png')
                        self.label_26.setPixmap(pixmap)
                    else:
                        pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Red' + '.png')
                        self.label_26.setPixmap(pixmap)          
                else:
                    self.label_24.setText(_translate("Connect_PDS_Window",'问题所在：\n电压偏差校核未通过'))
                    self.widget_18.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}") 
            else:
                self.label_23.setText(_translate("Connect_PDS_Window",'问题所在：\n短路电流校核未通过'))
                self.widget_3.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}")
                self.widget_18.setStyleSheet("QWidget{background-color:rgb(240, 243, 244);}")  
    
    
#第1页所有节点按钮连接槽函数及判断逻辑    
    def Page4_Select(self,item,column):
        _translate = QtCore.QCoreApplication.translate
        self.data = global_var.get_value('data')
        #button = self.widget_4.sender()
        #self.nowp = button.text()
        self.nowp = item.text(0)
        #print(self.nowp)
        self.label_31.setText('  方式名：' + self.data[self.nowp]['方式名'] + '     项目名：' + self.data[self.nowp]['项目名'])

        pixmap = QPixmap(global_var.get_value('direction') + 'files_generated' + os.sep + self.nowp +'.png')
        self.label_29.setPixmap(pixmap)
        self.label_29.setScaledContents(True)

        ab = self.data[self.nowp]['分布式光伏承载力']
        self.label_12.setText(_translate("MainWindow",str(ab)+'MW' ))

        if self.data[self.nowp]['评估等级']=='红色':
            pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Red' + '.png')
            self.label_28.setPixmap(pixmap)
            self.label_28.setAlignment(Qt.AlignCenter)
            self.label_8.setText(_translate("Connect_PDS_Window",'建议在负荷水平、电网安全性得到改善前，暂停分布式光\n伏接入。'))
        elif self.data[self.nowp]['评估等级']=='黄色':
            pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Yellow' + '.png')
            self.label_28.setPixmap(pixmap)
            self.label_28.setAlignment(Qt.AlignCenter)
            self.label_8.setText(_translate("Connect_PDS_Window",'建议对于确需接入的项目，应开展专项分析'))
        else:
            pixmap = QPixmap(global_var.get_value('direction') + "pic" + os.sep + 'Green' + '.png')
            self.label_28.setPixmap(pixmap)
            self.label_28.setAlignment(Qt.AlignCenter)
            self.label_8.setText(_translate("Connect_PDS_Window",'建议分布式光伏参考承载力结果优先接入。'))
    


#第三页数据填入
    def Page3_Table(self,bcard,lcard,tcard):
        row = numpy.shape(bcard)[0]
        self.model = QStandardItemModel(row, 19)
        self.model.setHorizontalHeaderLabels(['卡片子型', '修改码', '所有者代码','节点名称','基准电压(kV)','节点所在分区名称','有功恒定负荷(MW)','无功恒定负荷(MVar)','基准电压下的有功并联导纳负荷(MW)','基准电压下的无功并联导纳负荷(MVar)','最大有功出力(MW)','实际有功出力(MW)','（B）所安排的无功出力值(MVar)/（BQ、BS）无功出力最大值(MVar)','无功出力最小值(MVar)','所安排的电压值/Vmax(标幺值)','（B、BQ）所安排的Vmin(标幺值) /（BS）角度值','承载力','评估等级','问题所在'])
        for i in range(row):
            for column in range(19):
                item = QStandardItem(bcard[i,column])
                # 设置每个位置的文本值
                self.model.setItem(i, column, item)
                # print(item.text())
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中整行
        self.tableView.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中一行

        row_2 = numpy.shape(lcard)[0]
        self.model_2 = QStandardItemModel(row_2, 19)
        self.model_2.setHorizontalHeaderLabels(['修改码', '所有者代码','节点名1','基准电压(kV)','区域联络线测点标记','节点名2','基准电压(kV)','回路号','线路额定电流值(A)','并联线路数目','系统基准电压和基准容量下的电阻标幺值','系统基准电压和基准容量下的电抗标幺值','线路对地导纳标幺值G/2','线路对地导纳标幺值B/2','线路长度','线路说明数据','投运日期：月','投运日期：年','停运日期'])
        for i in range(row_2):
            for column in range(19):
                item = QStandardItem(lcard[i,column])
                # 设置每个位置的文本值
                self.model_2.setItem(i, column, item)
                # print(item.text())        
        self.tableView_2.setModel(self.model_2)
        self.tableView_2.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableView_2.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中整行
        self.tableView_2.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
        self.tableView_2.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中一行

        row_3 = numpy.shape(tcard)[0]
        self.model_3 = QStandardItemModel(row_3, 20)
        self.model_3.setHorizontalHeaderLabels(['卡片子型','修改码', '所有者代码','节点名1','基准电压(kV)','区域联络线测点标记','节点名2','基准电压(kV)','回路号','变压器额定容量 ','并联线路数目','由铜损引起的等效电阻标幺值','漏抗标幺值','由铁损引起的等效电导标幺值','激磁电纳标幺值','（T）节点1的分接头位置(kV)/（TP）移相器的固定移相角(度)','（T）节点2的分接头位置(kV)','投运日期：月','投运日期：年','停运日期'])
        for i in range(row_3):
            for column in range(20):
                item = QStandardItem(tcard[i,column])
                # 设置每个位置的文本值
                self.model_3.setItem(i, column, item)
                # print(item.text())       
        self.tableView_3.setModel(self.model_3)
        self.tableView_3.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        self.tableView_3.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中整行
        self.tableView_3.setEditTriggers(QTableView.NoEditTriggers)  # 不可编辑
        self.tableView_3.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置只能选中一行

#导出Excel按钮连接槽函数
    def exportToExcel(self):
        wb = Workbook()
        
        #导出B卡表单
        bcardl = global_var.get_value('bcard').tolist()
        ws1 = wb.create_sheet(title = "B card", index = 0)
        columnHeaders1 = ['卡片子型', '修改码', '所有者代码','节点名称','基准电压(kV)','节点所在分区名称','有功恒定负荷(MW)','无功恒定负荷(MVar)','基准电压下的有功并联导纳负荷(MW)','基准电压下的无功并联导纳负荷(MVar)','最大有功出力(MW)','实际有功出力(MW)','（B）所安排的无功出力值(MVar)/（BQ、BS）无功出力最大值(MVar)','无功出力最小值(MVar)','所安排的电压值/Vmax(标幺值)','（B、BQ）所安排的Vmin(标幺值) /（BS）角度值','承载力','评估等级','问题所在']
        # 添加表头
        for i in range(len(columnHeaders1)):
           ws1.cell(1,i+1).value = columnHeaders1[i]
         # 添加数据
        for r in range(len(bcardl)):
            ws1.append(bcardl[r])
            
        #导出L卡数据
        lcardl =  global_var.get_value('lcard').tolist()
        ws2 = wb.create_sheet(title = "L card",index = 1)
        columnHeaders2 = ['修改码', '所有者代码','节点名1','基准电压(kV)','区域联络线测点标记','节点名2','基准电压(kV)','回路号','线路额定电流值(A)','并联线路数目','系统基准电压和基准容量下的电阻标幺值','系统基准电压和基准容量下的电抗标幺值','线路对地导纳标幺值G/2','线路对地导纳标幺值B/2','线路长度','线路说明数据','投运日期：月','投运日期：年','停运日期']
        # 添加表头
        for i in range(len(columnHeaders2)):
           ws2.cell(1,i+1).value = columnHeaders2[i]
         # 添加数据
        for r in range(len(lcardl)):
            ws2.append(lcardl[r])
            
        #导出T卡数据
        tcardl = global_var.get_value('tcard').tolist()
        ws3 = wb.create_sheet(title = "T card",index = 2)
        columnHeaders3 = ['卡片子型','修改码', '所有者代码','节点名1','基准电压(kV)','区域联络线测点标记','节点名2','基准电压(kV)','回路号','变压器额定容量 ','并联线路数目','由铜损引起的等效电阻标幺值','漏抗标幺值','由铁损引起的等效电导标幺值','激磁电纳标幺值','（T）节点1的分接头位置(kV)/（TP）移相器的固定移相角(度)','（T）节点2的分接头位置(kV)','投运日期：月','投运日期：年','停运日期']
        for i in range(len(columnHeaders3)):
            ws3.cell(1,i+1).value = columnHeaders3[i]
        for r in range(len(tcardl)):
            ws3.append(tcardl[r])
        
        wb.save(global_var.get_value('direction') + 'files_generated' + os.sep + 'results.xlsx', )




class hiddenThread(QThread):

    def __init__(self, window):
        super().__init__()
        self.window=window

    def run(self):
        self.window.hidden()
 